package com.bbcare.department.plat.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.OSSClientUtil;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.service.IDepartmentBasicService;

@Controller
@RequestMapping("/service/department")
public class DepartmentBasicController {
    Logger logger = Logger.getLogger(DepartmentBasicController.class);
    @Autowired
    private IDepartmentBasicService deparmentBasicService;

    @ResponseBody
    @RequestMapping("/basicinfo/detail")
    public ResultModel<DepartmentBasic> getDepartmentBasic(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in getDepartmentBasic----arg==" + jsonStr);

        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");// 科室id
        DepartmentBasic departmentBasic = deparmentBasicService.getDepartmentBasicDetails(deptId);
        logger.info("out getDepartmentBasic----arg==" + departmentBasic);
        return new ResultModel<DepartmentBasic>(departmentBasic);
    }

    @ResponseBody
    @RequestMapping("/basicinfo/save")
    public ResultModel<Map<String, String>> saveDepartmentBasic(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in getDepartmentBasic----arg==" + jsonStr);
        // JSONObject jsonEsb = JSON.parseObject(jsonStr);
        DepartmentBasic departmentBasic = null;
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        String requestParam = jsonEsb.getString(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        departmentBasic = JSON.parseObject(requestParam, DepartmentBasic.class);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String createAuthor = (String) sessionMap.get("authorId");
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id
        // String deptId = (String) sessionMap.get("tenantId");// 租户id
        // 科室管理暂时都是修改
        if (StringUtils.isEmpty(departmentBasic.getId())) {
            departmentBasic.setCreateAuthor(createAuthor);
        } else {
            departmentBasic.setUpdateAuthor(createAuthor);
        }

        deptId = deparmentBasicService.departmentModify(departmentBasic);
        logger.info("out getDepartmentBasic----arg==" + departmentBasic);
        Map<String, String> rspBody = new HashMap<String, String>();
        rspBody.put("deptId", deptId);
        return new ResultModel<Map<String, String>>(rspBody);
    }

    @ResponseBody
    @RequestMapping("/basicinfo/modify")
    public ResultModel<Map<String, String>> modifydepartmentBasic(HttpServletRequest request,
            @RequestBody String jsonStr) throws Exception {
        logger.info("in getDepartmentBasic----arg==" + jsonStr);
        // JSONObject jsonEsb = JSON.parseObject(jsonStr);
        DepartmentBasic departmentBasic = null;
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        String requestParam = jsonEsb.getString(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        departmentBasic = JSON.parseObject(requestParam, DepartmentBasic.class);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String createAuthor = (String) sessionMap.get("authorId");
        String deptId = (String) sessionMap.get("rootGroupId");// 租户id

        // 科室管理暂时都是修改
        departmentBasic.setId(deptId);
        if (StringUtils.isEmpty(departmentBasic.getId())) {
            departmentBasic.setCreateAuthor(createAuthor);
        } else {
            departmentBasic.setUpdateAuthor(createAuthor);
        }

        deptId = deparmentBasicService.departmentModify(departmentBasic);
        logger.info("out getDepartmentBasic----arg==" + departmentBasic);
        Map<String, String> rspBody = new HashMap<String, String>();
        rspBody.put("deptId", deptId);
        return new ResultModel<Map<String, String>>(rspBody);
    }

    /**
     * 根据科室Id 查询账号流水
     *
     * @param jsonStr
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/account/list")
    public ResultModel<List<Map<String, String>>> getAccountBillsList(HttpServletRequest request,
            @RequestBody String jsonStr) throws Exception {
        logger.info("in list----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        /*
         * String doctorId = requestParam.getString("doctorId"); String workType
         * = requestParam.getString("workType");
         */

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String deptId = (String) sessionMap.get("rootGroupId");// 租户id

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);
        paramMap.put("deptId", deptId);
        List<Map<String, String>> accountBills = deparmentBasicService.getAccountBillsList(paramMap);
        logger.info("out getScheduleSByCondition----arg==" + accountBills);
        return new ResultModel<List<Map<String, String>>>(accountBills);
    }

    @ResponseBody
    @RequestMapping("/basicinfo/uploadPicture")
    public ResultModel<Object> uploadPicture(HttpServletResponse response, HttpServletRequest request)
            throws Exception {
        logger.info("in uploadPicture==");
        String filepath = "";
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            if (iter.hasNext()) {
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if (!file.isEmpty()) {
                        filepath = OSSClientUtil.uploadPicture(file, PropertiesUtils.getProperty("hospitalPicture"));// 保存图片
                    }
                }
            } else {
                throw new AppException(ErrorCode.FOLLOW_EXCEPTION_TYPE_UPLOAD_FILE_MPTY, "图片上传失败，上传文件为空");
            }
        }
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String createAuthor = (String) sessionMap.get("authorId");
        String deptId = (String) sessionMap.get("rootGroupId");// 租户id

        DepartmentBasic departmentBasic = new DepartmentBasic();
        departmentBasic.setId(deptId);
        departmentBasic.setHospPicture(filepath);
        departmentBasic.setUpdateAuthor(createAuthor);
        departmentBasic.setUpdateTime(DateUtil.getSysDateA());
        deparmentBasicService.departmentModify(departmentBasic);
        logger.info("in uploadPicture==uploadPicture:" + filepath);

        return new ResultModel<Object>(filepath);
    }

    @ResponseBody
    @RequestMapping("/basicinfo/uploadIcon")
    public ResultModel<Object> uploadIcon(HttpServletResponse response, HttpServletRequest request) throws Exception {
        logger.info("in uploadIcon==");
        String filepath = "";
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            if (iter.hasNext()) {
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if (!file.isEmpty()) {
                        filepath = OSSClientUtil.uploadPicture(file, PropertiesUtils.getProperty("hospitalLogo"));// 保存图片
                    }
                }
            } else {
                throw new AppException(ErrorCode.FOLLOW_EXCEPTION_TYPE_UPLOAD_FILE_MPTY, "图片上传失败，上传文件为空");
            }

        }
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String createAuthor = (String) sessionMap.get("authorId");
        String deptId = (String) sessionMap.get("rootGroupId");// 租户id
        DepartmentBasic departmentBasic = new DepartmentBasic();

        departmentBasic.setId(deptId);
        departmentBasic.setHospIcon(filepath);
        departmentBasic.setUpdateAuthor(createAuthor);
        departmentBasic.setUpdateTime(DateUtil.getSysDateA());
        deparmentBasicService.departmentModify(departmentBasic);
        logger.info("in uploadIcon==filepath:" + filepath);
        return new ResultModel<Object>(filepath);
    }

    @ResponseBody
    @RequestMapping("/basicinfo/uploadQrcode")
    public Object uploadQrcode(HttpServletResponse response, HttpServletRequest request) throws Exception {
        logger.info("in uploadPicture==");
        String filepath = "";
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            if (iter.hasNext()) {
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if (!file.isEmpty()) {
                        filepath = OSSClientUtil.uploadPicture(file, PropertiesUtils.getProperty("registerQrcode"));// 保存图片
                    }
                }
            } else {
                throw new AppException(ErrorCode.FOLLOW_EXCEPTION_TYPE_UPLOAD_FILE_MPTY, "图片上传失败，上传文件为空");
            }

        }
        logger.info("in uploadPicture==filepath:" + filepath);
        return new ResultModel<Object>(filepath);
    }

    // 科室随访门诊排班增加
    @ResponseBody
    @RequestMapping("/randOutPatientScheduleAdd")
    public ResultModel<Map<String, Object>> saveRandOutPatientSchedule(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
        logger.warn("in saveRandOutPatientSchedule----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        JSONObject jsonSchedule = jsonData.getJSONObject("scheduleInfo");
        if (null == jsonSchedule) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，无scheduleInfo节点！"));
        }
        String scheduleType = jsonSchedule.getString("scheduleType");
        if (null == scheduleType || "".equals(scheduleType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，排班类型未传或值为空！"));
        }
        String workDay = jsonSchedule.getString("workDay");
        if (null == workDay || "".equals(workDay)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，工作日未传或值为空！"));
        }
        String workPeriod = jsonSchedule.getString("workPeriod");
        if (null == workPeriod || "".equals(workPeriod)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，工作时段未传或值为空！"));
        }

        JSONObject jsonOpInfo = jsonData.getJSONObject(Constants.INF_INPUTPARAM_OPRINFO_FIELD);
        if (null == jsonOpInfo) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无oprInfo节点！"));
        }
        String opCode = jsonOpInfo.getString("opCode");
        if (StringUtils.isEmpty(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码节点或值为空！"));
        }
        String opType = jsonOpInfo.getString("opType");
        if (StringUtils.isEmpty(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作类型节点或值为空！"));
        }
        String opNote = jsonOpInfo.getString("opNote");
        if (StringUtils.isEmpty(opNote)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码备注或值为空！"));
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        int groupType = (Integer) sessionMap.get("groupType");// 组织类型
        String rootGroupId = (String) sessionMap.get("rootGroupId");// 组织id

        paramMap.put("authorName", authorName);
        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        paramMap.put("scheduleType", scheduleType);
        paramMap.put("workDay", workDay);
        paramMap.put("workPeriod", workPeriod);
        paramMap.put("updateTime", currTime);
        paramMap.put("updateAccept", updateAccept);
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("groupType", groupType);
        paramMap.put("rootGroupId", rootGroupId);
        paramMap.put("opCode", opCode);
        paramMap.put("opType", opType);
        paramMap.put("opNote", opNote);

        Map<String, Object> retMap = deparmentBasicService.saveRandOutPatient(paramMap);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 科室随访门诊排班删除
    @ResponseBody
    @RequestMapping("/randOutPatientScheduleDel")
    public ResultModel<Map<String, Object>> removeRandOutPatientSchedule(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
        logger.warn("in removeRandOutPatientSchedule----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        JSONObject jsonSchedule = jsonData.getJSONObject("scheduleInfo");
        if (null == jsonSchedule) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，无scheduleInfo节点！"));
        }
        String scheduleId = jsonSchedule.getString("scheduleId");
        if (null == scheduleId || "".equals(scheduleId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，排班id未传或值为空！"));
        }

        JSONObject jsonOpInfo = jsonData.getJSONObject(Constants.INF_INPUTPARAM_OPRINFO_FIELD);
        if (null == jsonOpInfo) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无oprInfo节点！"));
        }
        String opCode = jsonOpInfo.getString("opCode");
        if (StringUtils.isEmpty(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码节点或值为空！"));
        }
        String opType = jsonOpInfo.getString("opType");
        if (StringUtils.isEmpty(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作类型节点或值为空！"));
        }
        String opNote = jsonOpInfo.getString("opNote");
        if (StringUtils.isEmpty(opNote)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码备注或值为空！"));
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        int groupType = (Integer) sessionMap.get("groupType");// 组织类型
        String rootGroupId = (String) sessionMap.get("rootGroupId");// 组织id

        paramMap.put("authorName", authorName);
        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        paramMap.put("scheduleId", scheduleId);
        paramMap.put("updateTime", currTime);
        paramMap.put("updateAccept", updateAccept);
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("groupType", groupType);
        paramMap.put("rootGroupId", rootGroupId);
        paramMap.put("opCode", opCode);
        paramMap.put("opType", opType);
        paramMap.put("opNote", opNote);

        Map<String, Object> retMap = deparmentBasicService.removeRandOutPatient(paramMap);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 科室随访门诊排班查询
    @ResponseBody
    @RequestMapping("/randOutPatientScheduleList")
    public ResultModel<Map<String, Object>> listRandOutPatientSchedule(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
        logger.warn("in listRandOutPatientSchedule----arg==" + arg);

        Map<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        int groupType = (Integer) sessionMap.get("groupType");// 组织类型
        String rootGroupId = (String) sessionMap.get("rootGroupId");// 组织id

        paramMap.put("authorName", authorName);
        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("groupType", groupType);
        paramMap.put("rootGroupId", rootGroupId);

        Map<String, Object> retMap = deparmentBasicService.listRandOutPatient(paramMap);

        return new ResultModel<Map<String, Object>>(retMap);
    }
}
